package com.atguigu.gulimall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.model.vo.MemberResponseVo;
import com.atguigu.common.utils.R;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginAndRegController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 发送一个请求，直接跳转到一个页面
     * <p>
     * Spring MVC viewController:将请求和页面映射过来
     * <p>
     * GulimallWebConfig 配置了以下跳转路径
     *
     * @GetMapping({"/", "/login"})
     * public String login() {
     * return "login";
     * }
     * @GetMapping({"/registry"}) public String registry() {
     * return "registry";
     * }
     */
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String code = UUID.randomUUID().toString().substring(0, 6);
        //1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(redisCode)) {
            String[] codeAndTime = redisCode.split("_");
            if (codeAndTime.length > 1) {
                long preTime = Long.parseLong(codeAndTime[1]);
                if (System.currentTimeMillis() - preTime < 60000) {
                    //60秒内不可再发
                    return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
                }
            }
        }
        //2、验证码的再次校验 redis,防止同一个手机号再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 5, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    //转发    forward
    //重定向   redirect
    //重定向携带数据，利用session原理，将数据放在session中。跳到下个页面，取出数据后，session的数据会删除 RedirectAttributes
    //BindingResult 获取校验错误信息
    //todo 分布式下的session问题
    @PostMapping("/user/registry")
    public String registry(@Valid UserRegistryVo userRegistryVo, BindingResult result, RedirectAttributes model) {
        if (result.hasErrors()) {
            //校验出错，转发到注册页 todo 校验
            Map<String, String> errors = result.getFieldErrors().stream().distinct().collect(Collectors.toMap(FieldError::getField, DefaultMessageSourceResolvable::getDefaultMessage));
            model.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/registry";
        }
        //调用远程服务，注册
        //校验验证码
        String code = userRegistryVo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistryVo.getPhone());
        Map<String, String> errors = new HashMap<>();
        if (StringUtils.isNotEmpty(redisCode)) {
            String preCode = redisCode.split("_")[0];
            if (code.equals(preCode)) {
                //验证码通过，注册
                R r = memberFeignService.registry(userRegistryVo);
                if (r.getCode() == 0) {
                    //注册成功,验证码删除,回到登录页
                    redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistryVo.getPhone());
                    return "redirect:http://auth.gulimall.com/login";
                } else {
                    //注册失败
                    errors.put("msg", (String) r.get("msg"));
                }
            } else {
                errors.put("code", "验证码错误");
            }
        }
        errors.put("code", "验证码已过期");
        model.addFlashAttribute("errors", errors);
        return "redirect:http://auth.gulimall.com/registry";
    }

    @GetMapping("/login")
    public String loginPage(HttpSession session) {
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (loginUser != null) {
            return "redirect:http://gulimall.com";
        }
        return "login";
    }

    //表单提交的请求方式 参数以kv对传递，此处不能用 @RequestBoyd 转 json
    @PostMapping("/user/login")
    public String login(@Valid UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        //远程登录
        R login = memberFeignService.login(userLoginVo);
        if (login.getCode() == 0) {
            MemberResponseVo data = login.getData(new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://gulimall.com";
        } else {
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", (String) login.get("msg"));
            //todo 登录错误的提示            redirectAttributes.addFlashAttribute("errors", errors);
            session.setAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login";
        }
    }


}
